"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from PyQt4 import QtGui
from PyQt4 import QtCore
from msnp.gui import UIText, Resources, GUIHelper, MyStyle
from msnp import gui
from msnp.model import DatabaseModel
from msnp.persistence import XMLController
from msnp.logger import Logger
from msnp.service.network import LeaveRequest

class DBErrorWidget(QtGui.QDialog):
    """This class represents an error widget to inform the user about database errors.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __mainLayout: A QVBoxLayout object containing the items __txtDescription, __tracebackWidget and __butOk.
        __errorType: A DBErrorType object, one of SELECT, INSERT, UPDATE, DELETE, INIT, CHECK, DROP, TRIGGER or UNKNOWN.
        __dbType: A DatabaseType object, one of MEDIA, PLAYER or PTP.
        __traceback: A String object containing the traceback text of the error.
        __txtDescription: A QTextEdit object.
        __tracebackWidget: A QWidget object containing the items __lblTraceback and __txtTraceback.
        __lblTraceback: A QLabel object.
        __txtTraceback: A QTextEdit object.
        __butOk: A QPushButton object connected to the method __ok().
    """
    def __init__(self, dbType, errorType, traceback, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__errorType = errorType
        self.__dbType = dbType
        self.__traceback = traceback
        self.setWindowTitle(UIText.TITLE_DB_ERROR)
        self.setWindowIcon(QtGui.QIcon(Resources.IMAGE_DB_ERROR_ICON))
        self.setFixedSize(400, 300)
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
        GUIHelper.centerWidget(self)
        
    def __build(self):
        """Initializes the item __mainLayout and adds its contained items."""
        self.__initErrorTextfield()
        self.__initTracebackTextField()
        self.__initTracebackLabel()
        self.__initTracebackWidget()
        self.__initButton()
        self.__mainLayout.addWidget(self.__txtDescription)
        self.__mainLayout.addWidget(self.__tracebackWidget)
        self.__mainLayout.addWidget(self.__butOK)
        self.connect(self, QtCore.SIGNAL("triggered()"), self.closeEvent)
        
    def __initErrorTextfield(self):
        """Initializes the item __txtDescription."""
        self.__txtDescription = QtGui.QTextEdit()
        if self.__dbType == DatabaseModel.DatabaseType.PTP:
            self.__txtDescription.setText(UIText.MSG_DB_EXCEPTION_PTPDB)
        elif self.__dbType == DatabaseModel.DatabaseType.MEDIA:
            self.__txtDescription.setText(UIText.MSG_DB_EXCEPTION_MEDIADB)
        else:
            self.__txtDescription.setText(UIText.MSG_DB_EXCEPTION_PLAYERDB)
#        self.__txtDescription.setDisabled(True)
        self.__txtDescription.setReadOnly(True)
        
    def __initTracebackWidget(self):
        """Initializes the item __tracebackWidget and adds its contained items."""
        layout = QtGui.QVBoxLayout()
        self.__tracebackWidget = QtGui.QWidget()
        layout.addWidget(self.__lblTraceback)
        layout.addWidget(self.__txtTraceback)
        self.__tracebackWidget.setLayout(layout)
        
    def __initTracebackTextField(self):
        """Initializes the item __txtTraceback."""
        self.__txtTraceback = QtGui.QTextEdit()
        self.__txtTraceback.setFont(MyStyle.getFont10())
        self.__txtTraceback.setText(self.__traceback)
#        self.__txtTraceback.setDisabled(True)
        self.__txtTraceback.setReadOnly(True)
        
    def __initTracebackLabel(self):
        """Initializes the item __lblTraceback."""
        self.__lblTraceback = QtGui.QLabel(UIText.LABEL_DB_ERROR + ":")
        self.__lblTraceback.setFont(MyStyle.getFont15Bold())
        
    def __initButton(self):
        """Initializes the item __butOk."""
        self.__butOK = QtGui.QPushButton(UIText.BUT_DISCARD, self)
        self.__butOK.setFocusPolicy(QtCore.Qt.NoFocus)
        #register handler
        self.connect(self.__butOK, QtCore.SIGNAL('clicked()'), self.__ok)
        
    def __ok(self):
        """This method is connected to the QPushButton object __butOk."""
        self.destroy()
        gui.GUIController.resetDBErrorWidget()
        self.__executeClose()
        
    def closeEvent(self, event):
        """This method is called when the user closes the widget. Calls the method __ok() and ignores the event."""
        self.__ok()
        event.ignore()
        
    def __executeClose(self):
        """This method is called by the method __ok()."""
        if self.__dbType == DatabaseModel.DatabaseType.PTP:
            settings = XMLController.readAllSettings()
            Logger.info("Try to delete msnp database settings.")
            settings.getCurrentUserSettings().getMSNPDatabaseSettings().deleteDBSettings()
            XMLController.storeSettings(settings)
            LeaveRequest.requestFinish(True)
